package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.system.domain.Book;
import com.ruoyi.system.domain.Category;
import com.ruoyi.system.mapper.BookMapper;
import com.ruoyi.system.mapper.CategoryMapper;
import com.ruoyi.system.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 书籍Service业务层处理
 *
 * @author ruoyi
 * @date 2022-12-08
 */
@Service
public class BookServiceImpl implements IBookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 查询书籍
     *
     * @param id 书籍主键
     * @return 书籍
     */
    @Override
    public Book selectBookById(Long id) {
        return bookMapper.selectBookById(id);
    }

    /**
     * 查询书籍列表
     *
     * @param book 书籍
     * @return 书籍
     */
    @Override
    public List<Book> selectBookList(Book book) {
        book.setCategoryIdList(new ArrayList<>());
        Category category = categoryMapper.selectCategoryById(book.getCategoryId());
        if (BeanUtil.isNotEmpty(category) && 0 == category.getParentId()){
           List<Long> cidList = categoryMapper.selectCategoryByParentId(category.getId());
            cidList.forEach(item ->{
                book.getCategoryIdList().add(item);
            });
        }
        Long categoryId = book.getCategoryId();
        if (BeanUtil.isNotEmpty(category)){
            book.getCategoryIdList().add(categoryId);
        }
        return bookMapper.selectBookList(book);
    }

    /**
     * 新增书籍
     *
     * @param book 书籍
     * @return 结果
     */
    @Override
    public int insertBook(Book book) {
        return bookMapper.insertBook(book);
    }

    /**
     * 修改书籍
     *
     * @param book 书籍
     * @return 结果
     */
    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    /**
     * 批量删除书籍
     *
     * @param ids 需要删除的书籍主键
     * @return 结果
     */
    @Override
    public int deleteBookByIds(Long[] ids) {
        return bookMapper.deleteBookByIds(ids);
    }

    /**
     * 删除书籍信息
     *
     * @param id 书籍主键
     * @return 结果
     */
    @Override
    public int deleteBookById(Long id) {
        return bookMapper.deleteBookById(id);
    }

    @Override
    public List<Book> selectBookByCategoryIds(Long[] ids) {
        return null;
    }
}
